//
//  CustomTabBar.m
//  CustomTabBar
//
//  Created by 张琦 on 2016/10/24.
//  Copyright © 2016年 张琦. All rights reserved.
//

#import "CustomTabBar.h"
#import "CustomTabBarButton.h"

@interface CustomTabBar ()

@property (nonatomic, strong) NSMutableArray *arrTarBarItem;
@property (nonatomic, strong) CustomTabBarButton *selectItem; // 选中的item
@end

@implementation CustomTabBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.arrTarBarItem = [NSMutableArray array];
    }
    return self;
}

- (void)addCustomTabBarButtonWithItem:(UITabBarItem *)item {
    CustomTabBarButton *tabBarButton = [[CustomTabBarButton alloc] init];
    tabBarButton.tabBarItem = item;
    [self addSubview:tabBarButton];
    [self.arrTarBarItem addObject:tabBarButton];
    [tabBarButton addTarget:self action:@selector(clickCustomTabBarButton:) forControlEvents:UIControlEventTouchDown];
    //default selected first one
    if (self.arrTarBarItem.count == 1) {
        [self clickCustomTabBarButton:tabBarButton];
    }
}

- (void)clickCustomTabBarButton:(CustomTabBarButton *)item {
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectedButtonFrom:item.tag to:item.tag];
    }
    self.selectItem.selected = NO;
    item.selected = YES;
    self.selectItem = item;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat btnY = 0;
    CGFloat btnW = self.frame.size.width/(self.subviews.count);
    CGFloat btnH = self.frame.size.height;
    for (int i = 0; i < self.arrTarBarItem.count; i++) {
        CGFloat btnX = btnW * i;
        CustomTabBarButton *item = self.arrTarBarItem[i];
        item.frame = CGRectMake(btnX, btnY, btnW, btnH);
        item.tag = i;
    }

}

@end
